package models;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.imageio.ImageIO;
import javax.persistence.*;

import org.joda.time.DateTime;

import play.data.validation.MaxSize;
import play.data.validation.Required;
import play.db.DB;
import play.db.jpa.*;
 
@Entity
public class Course extends Model 
{
	@Required
	@MaxSize(50)
	public String titre_course;
	
	@Required
	public Date date_debut_course;

	@Required
	public Date date_fin_course;

	@Required
	public Date date_fin_inscription;
	
	@ManyToOne
    public Modele_course modele;
	
	@OneToMany(mappedBy="course", cascade=CascadeType.ALL)
	public List<Participe> participes;
	

	public Course(String titre_course, Date date_debut_course,
			Date date_fin_course, Date date_fin_inscription,
			Modele_course modele) 
	{
		this.participes = new ArrayList<Participe>();
		this.titre_course = titre_course;
		this.date_debut_course = date_debut_course;
		this.date_fin_course = date_fin_course;
		this.date_fin_inscription = date_fin_inscription;
		this.modele = modele;
	}

	public int getNbParticipant()
	{
		return this.participes.size();
	}
	
	public void addParticipant(Bateau b)
	{
		Participe p = new Participe(this, b);
		this.participes.add(p);
	}
	
	public boolean enCours()
	{
		Date d = new Date();
		return (d.after(this.date_debut_course) && d.before(this.date_fin_course));
	}
	
	public boolean terminer()
	{
		Date d = new Date();
		return (d.after(this.date_fin_course));
	}
	
	public boolean tropTard()
	{
		Date d = new Date();
		return (d.after(this.date_fin_inscription));
	}
	
	public String getDateFormater(Date date)
	{
		DateFormat jmahs = new SimpleDateFormat("'le' dd/MM/yyyy 'à' H'h'mm");
		return jmahs.format(date);
	}
	
	public String toString()
	{
		return this.date_debut_course.toString() + ": " + this.titre_course; 
	}	
	
	// Initialise les bateaux de la course à la position de la ville de départ
	public void demarrerCourse()
	{
		Iterator<Participe> itor = this.participes.iterator();
		
		System.out.println("Coordonnees de la ville de depart : " + this.modele.ville_depart.coordonnee);
		
		while(itor.hasNext())
		{
			Participe p = itor.next();
			Bateau bateau_courant = p.bateau;
			System.out.println("Le bateau " + bateau_courant.nom + " va être traitée");
			bateau_courant.coordonnee = this.modele.ville_depart.coordonnee;
			bateau_courant.save();
			System.out.println("Traité");
		}
		
	}
}
